<template>
  <div class="h-p100 w-p100">
    <div class="box box-ver h-p100 of-y-s">
      <div class="head box box-ac box-jc">
        <div class="business-container box box-ac">
          <div @click="changeTag(index,'businessType')" :value="item" :key="index" v-for="(item, index) in businessType.list" :class="{act:index==businessType.checkedIndex}" class="item box box-f1 box-ac box-pc box-ver">
            <div :class="'icon-business'+index" class="icon animated"></div>
            <div class="text">{{item.name}}</div>
          </div>
        </div>
      </div>
      <div v-if="JM==='FB'" class="tips box box-ac">
        <div class="icon icon-invoice-tips"></div>
        <div class="tc-666">
          若商家提供的纸质发票，请点击<span @click="goBaoXiao(0)" class="tc-main">我想报销纸质发票</span>
        </div>
      </div>
      <div ref="wrapper" class="box-f1 bill-container wrapper of-y-h">
        <div class="content box box-ver">
          <div v-if="billList && billList.length === 0" class="no-data box-f1">
            <div class="content box box-ver box-ac box-jc tc-999">
              <div class="icon icon-not-bill"></div>
              <div>小主，暂无可选发票，赶紧去添加哟~</div>
            </div>
          </div>
          <div class="list box box-ver">
            <div @tap="checkBill(index)" :value="bill" :key="index" v-for="(bill, index) in billList" class="bill-item box">
              <div class="checkbox box box-ac box-jc">
                <div :class="{'act': bill.checked === true}" class="icon icon-checkbox"></div>
              </div>
              <div class="bill-content box box-f1 box-ver">
                <div class="date">
                  {{bill.invoicedate}}
                </div>
                <div class="box box-ac">
                  <div class="salesname ell box-f1">{{bill.salesname}}&nbsp;</div>
                  <div class="money">¥{{bill.totalamount}}</div>
                </div>
                <div class="status box box-ac">
                  <div v-if="bill.invoicetype == '04' || bill.invoicetype == '10'" class="icon icon-status icon-status1"></div>
                  <div v-if="bill.invoicetype == '01'" class="icon icon-status icon-status2"></div>
                  <div v-if="bill.invoicetype == '10'" class="icon icon-status icon-status3"></div>
                  <div v-if="bill.invoicetype == '04' || bill.invoicetype == '01'" class="icon icon-status icon-status4"></div>
                  <div v-if="bill.usestate == '1'" class="icon icon-status icon-status5"></div>
                  <div v-if="bill.usestate == '2'" class="icon icon-status icon-status6"></div>
                  <div v-if="bill.ckstatus == '1'" class="icon icon-status icon-status7"></div>
                  <div class="box-f1 "></div>
                  <div class="type tc-999">
                    {{businessType.list[+bill.detailedtype || 4].name}}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-if="billList.length > 0" class="box tc-666 box-ac total">
        <div @click="checkAll" class="box box-ac">
          <div :class="{act: checkedInvoice.list.length === billList.length}" class="icon icon-checkbox"></div>
          <div >全选</div>
        </div>
        <div class="box-f1"></div>
        <div>
          已选择
          <span class="tc-main">{{checkedInvoice.num}}</span>
          张，总金额
          <span class="tc-main">¥{{checkedInvoice.money | formatMoney}}</span>
        </div>
      </div>
      <div class="bottom box box-ac">
        <div @click="addInvoice()" class="btn box box-f1 box-ac box-jc w-p100">{{JM === 'FB'?'从微信卡包导入':'从发票包添加'}}</div>
        <div @click="next()" class="btn box box-f1 box-ac box-jc w-p100">已选发票去报销</div>
      </div>
    </div>
  </div>

</template>

<script>
// import BScroll from 'better-scroll'
import { openToast } from '@/assets/js/tools'
import { mapState } from 'vuex'
import { formatDate, formatMoney } from '@/assets/js/filters'
import BScroll from 'better-scroll'
export default {
  data () {
    return {
      JM: '',
      billList: [],
      checkedInvoice: {
        type: null,
        num: 0,
        money: 0,
        list: []
      },
      pageNo: 0,
      scroll: null,
      businessType: {
        checkedIndex: 0,
        list: [{
          name: '全部',
          id: ''
        }, {
          name: '住宿费',
          id: 1
        }, {
          name: '餐饮费',
          id: 2
        }, {
          name: '通讯费',
          id: 3
        }, {
          name: '其他',
          id: 4
        }]
      }
    }
  },
  computed: mapState(['userNum', 'userInfo', 'bizAccountBill']),
  created () {
    let JM = this.$route.query.JM
    this.JM = JM
    if (JM === 'FB') {
      if (!this.bizAccountBill.expenseNum) return this.$router.replace('/')
      let expenseType = this.bizAccountBill.expenseType || ''
      if (expenseType === 'tel') {
        this.businessType.checkedIndex = 3
      }
    } else if (JM === 'CB20') {
      this.businessType.checkedIndex = 1
    }
    this.$nextTick(() => {
      if (!this.scroll) {
        this.scroll = new BScroll(this.$refs.wrapper, {
          tap: true,
          pullUpLoad: {
            threshold: -50
          }
        })
        this.scroll.on('pullingUp', pos => {
          this.pageNo++
          this.findListInvoice(this.pageNo)
        })
        this.findListInvoice(this.pageNo)
      }
    })
  },
  methods: {
    calculateMoney () {
      let checkedInvoice = {
        num: 0,
        money: 0,
        list: []
      }
      this.billList.forEach(item => {
        if (item.checked) {
          checkedInvoice.num++
          checkedInvoice.money += (+item.totalamount)
          if (this.JM === 'FB') {
            checkedInvoice.list.push(item.tabid)
          } else if (this.JM === 'CB20') {
            checkedInvoice.list.push(item)
          }
        }
      })
      checkedInvoice.money = formatMoney(checkedInvoice.money)
      this.checkedInvoice = checkedInvoice
    },
    changeTag (index, data) {
      if (this[data].checkedIndex !== index) {
        this[data].checkedIndex = index
        this.pageNo = 0
        this.findListInvoice()
        this.checkedInvoice = {
          num: 0,
          money: 0,
          list: []
        }
      }
    },
    checkBill (index) {
      this.billList[index].checked = !this.billList[index].checked
      this.calculateMoney()
    },
    checkAll () {
      if (this.checkedInvoice.list.length === this.billList.length) {
        this.billList.forEach(item => {
          item.checked = false
        })
      } else {
        this.billList.forEach(item => {
          item.checked = true
        })
      }
      this.calculateMoney()
    },
    next () {
      if (this.JM === 'FB') {
        this.goBaoXiao(1)
      } else if (this.JM === 'CB20') {
        this.backCaiBao()
      }
    },
    // 返回差报发住宿费填写页面
    backCaiBao () {
      if (this.checkedInvoice.list.length === 0) {
        return this.$tools.openToast({
          msg: '请至少选择一张发票',
          duration: 2000
        })
      }
      if (this.checkedInvoice.list.length > 0) {
        this.$emit('caiBaoInvoiceCallBack', {
          ...this.checkedInvoice
        })
      }
      this.$router.go(-1)
    },
    // iseinvoice   1-带电子发票 0-不带电子发票
    goBaoXiao (iseinvoice) {
      if (iseinvoice === 1 && this.checkedInvoice.list.length === 0) { // 电子发票发票
        return this.$tools.openToast({
          msg: '请至少选择一张发票',
          duration: 2000
        })
      } else {
        this.$store.commit('bizAccountBill', {
          amount: ''
        })
      }
      if (iseinvoice === 0) {
        this.checkedInvoice.list = null
      }
      let { userName, payeeAccount, payeeBank, companyNum, depNum, companyName, depName } = this.userInfo
      let bizReqDate = formatDate(new Date(), 'yyyy-MM-dd')
      this.$store.commit('bizAccountBill', {
        iseinvoice,
        checkedInvoice: this.checkedInvoice,
        personName: userName,
        payeeAccount: payeeAccount,
        payeeBank: payeeBank,
        companyNum,
        costDeptNum: depNum,
        companyName,
        costCenterName: depName,
        bizReqDate,
        billNum: '',
        state: ''
      })
      this.$router.push('/baoxiaoStep2')
    },
    findListInvoice () {
      let nowDate = formatDate(new Date(), 'yyyy-MM')
      let nowYear = nowDate.split('-')[0]
      if (+nowDate.split('-')[1] < 4) {
        nowYear--
      }
      // alert(`${nowYear}-01-01`)
      let datasource = '2;4'
      if (this.JM === 'CB20') {
        datasource = ''
      }
      this.$http({
        type: 'XML',
        method: 'post',
        url: this.$config.api.GXUrl + '/CheckInvoice/services/AutoImageCenter.ws?wsdl',
        data: {
          servername: 'FindListInvoice',
          data: {
            useraccount: this.userNum,
            invoicecode: '',
            invoicenum: '',
            startdate: `${nowYear}-01-01`,
            enddate: '2030-01-01',
            usestate: 2,
            pagesize: 50,
            invoicetype: '',
            datasource,
            // datasource: '1;2;3;4',
            detailedtype: this.businessType.list[this.businessType.checkedIndex].id,
            pageindex: this.pageNo
          }
        }
      }).then(item => {
        this.scroll.finishPullUp()
        if (+item.result['#text'] === 0) {
          let billList = []
          if (this.pageNo === 0) {
            this.billList = []
          }
          if (!item.invoices) {
            if (this.pageNo !== 0) {
              openToast({
                msg: '暂无更多数据',
                duration: 1500
              })
            } else {
              console.log('无发票')
            }
            this.pageNo--
            return
          } else {
            billList = [].concat(item.invoices.invoice)
          }
          let getVal = (obj, key) => {
            if (obj[key]) {
              return obj[key]['#text'] || ''
            } else {
              return ''
            }
          }
          // console.log(billList)
          // billList = [].concat(billList, billList, billList, billList, billList, billList, billList, billList)
          let newBillList = []
          let hasSelectedList = sessionStorage.getItem('hasSelectedList')
          if (this.JM === 'CB20') hasSelectedList = JSON.parse(hasSelectedList)
          // console.log('hasSelectedList>>>', hasSelectedList)
          billList.forEach(item => {
            let hasItem = false
            if (this.JM === 'CB20') {
              hasSelectedList.forEach(item1 => {
                console.log(item1.tabid, getVal(item, 'tabid'))
                if (getVal(item, 'tabid') === item1.tabid) {
                  hasItem = true
                }
              })
            }
            console.log(hasItem)
            if (!hasItem) {
              newBillList.push({
                checked: false,
                tabid: getVal(item, 'tabid'),
                invoicecode: getVal(item, 'invoicecode'),
                invoicenum: getVal(item, 'invoicenum'),
                invoicedate: getVal(item, 'invoicedate'),
                invoiceamount: getVal(item, 'invoiceamount'),
                totalamount: getVal(item, 'totalamount'),
                remark: getVal(item, 'remark'),
                ckstatus: getVal(item, 'ckstatus'),
                datasource: getVal(item, 'datasource'),
                usestate: getVal(item, 'usestate'),
                invoicetype: getVal(item, 'invoicetype'),
                buyername: getVal(item, 'buyername'),
                salesname: getVal(item, 'salesname'),
                checkcode: getVal(item, 'checkcode'),
                pdfuuid: getVal(item, 'pdfuuid'),
                filepath: getVal(item, 'filepath'),
                detailedtype: getVal(item, 'detailedtype'),
                detailse: getVal(item, 'detailse'),
                detailsl: getVal(item, 'detailsl')
              })
            }
          })
          this.billList = newBillList
          // console.log('发票列表', this.billList)
          this.$nextTick(() => {
            this.scroll.refresh()
          })
        }
      })
    },
    // 添加发票
    addInvoice () {
      if (this.JM === 'FB') {
        this.$http({
          url: `/vank/receipt/param_for_list1.do`,
          data: {}
        }).then(res => {
          console.log('获取发票微信配置', JSON.stringify(res))
          let billConfig = res.data
          wx.invoke('chooseInvoice', billConfig, res => {
            console.log(JSON.stringify(res))
            let chooseInvoiceInfo = res.choose_invoice_info || '[]'
            chooseInvoiceInfo = JSON.parse(chooseInvoiceInfo)
            if (chooseInvoiceInfo.length > 0) {
              this.$store.state.chooseInvoiceInfo = chooseInvoiceInfo
              this.$router.replace('/wxInvoiceList')
            }
          })
        })
      } else if (this.JM === 'CB20') {
        window.open(this.$config.url.invoice)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../assets/css/config';
@import '../assets/css/mixins';
.tips{
  font-size:.28rem;
}
.head{
  height:1.78rem;
  width:100%;
  background-color:$themeColor;
}
.no-data{
  .content{
    height:4.4rem;
    background-color: #fff;
    font-size:.22rem;
    .icon-not-bill{
      width:1.64rem;
      height:1.2rem;
      margin-bottom:.4rem;
      @include bg-image('../assets/images/icon-not-bill')
    }
  }
}
.total{
  height:.9rem;
  padding:0 .5rem;
  padding-left: .24rem;
  background-color:#FFF;
  font-size:.24rem;
  .icon-checkbox{
    margin-right:.1rem;
  }
}
.bottom{
  background-color: $themeColor;
  height:1rem;
  .btn{
    color:#FFF;
    height:.9rem;
    &:nth-of-type(1){
      border-right:1px solid #FFF;
    }
  }
}
.business-container{
  background-color:#FFF;
  width:6.9rem;
  height:1.1rem;
  border-radius:.2rem;
  background-color: #FFF;
  .item{
    color:#777;
    font-size:.22rem;
    .icon{
      width:.6rem;
      height:.6rem;
      border-radius:50%;
      margin-bottom:.05rem;
    }
    @for $i from 0 through 4 {
      .icon-business#{$i} {
        @include bg-image('../assets/images/icon-business#{$i}');
      }
    }
    &.act{
      color:$themeColor;
      .icon{
        animation-name: rubberBand;
      }
      @for $i from 0 through 4 {
        .icon-business#{$i} {
          @include bg-image('../assets/images/icon-business#{$i}-act');
        }
      }
    }
  }
}
.list{
  .bill-item{
    margin-bottom:.2rem;
    height:1.7rem;
    background-color:#FFF;
    .checkbox{
      width:.9rem;
      height:100%;
      border-right:1px solid $borderColor;
    }
    .bill-content{
      padding:.2rem .4rem;
      color:#666;
      .date{
        color:#999;
        font-size:.26rem;
        padding-bottom:.24rem;
      }
      .salesname{
        width:4.5rem;
        font-size:.28rem;
      }
      .money{
        color:#999;
        font-size:.36rem;
      }
      .status{
        margin-top:.2rem;
      }
      .type{
        font-size:.26rem;
        padding-right:.3rem;
      }
      .icon-status{
        width:.3rem;
        height:.31rem;
        margin-top:.1rem;
        margin-bottom:.1rem;
        margin-right:.2rem;
      }
      .icon-status5,.icon-status6{
        width:.6rem;
        height:.31rem;
      }
      .icon-status7{
        width:.28rem;
        height:.33rem;
      }
      @for $i from 1 through 7 {
        .icon-status#{$i} {
          @include bg-image('../assets/images/icon-status#{$i}');
        }
      }
    }
  }
}
</style>
